from deepdiff import DeepDiff

# 定义两个包含字典的列表进行比较
list1 = [
    {"id": 1, "name": "Alice", "age": 30},
    {"id": 2, "name": "Bob", "hobbies": ["reading", "swimming"]},
    {"id": 3, "name": "Charlie", "scores": [95, 88, 92]}
]

list2 = [
    {"id": 1, "name": "Alice", "age": 31},  # 年龄值变更
    {"id": 2, "name": "Robert", "hobbies": ["reading", "hiking"]},  # 名字和爱好变更
    {"id": 4, "name": "David", "extra": "field"}  # 新增项
    # 缺少id=3的项
]

# 比较两个列表（不考虑顺序）
diff = DeepDiff(list1, list2, ignore_order=True)
# 排除hobbies属性
# diff = DeepDiff(list1, list2, ignore_order=True, exclude_paths=["*.hobbies"])

# 输出比较结果
print("### 字典列表差异分析 ###")

if 'values_changed' in diff:
    print("\n1. 值变更:")
    for key, value in diff['values_changed'].items():
        print(f"  - {key}:")
        print(f"    旧值: {value['old_value']}")
        print(f"    新值: {value['new_value']}")

if 'iterable_item_added' in diff:
    print("\n2. 新增项:")
    for item in diff['iterable_item_added']:
        print(f"  - {item}")

if 'iterable_item_removed' in diff:
    print("\n3. 删除项:")
    for item in diff['iterable_item_removed']:
        print(f"  - {item}")

if 'dictionary_item_added' in diff:
    print("\n4. 字典中新增的字段:")
    for item in diff['dictionary_item_added']:
        print(f"  - {item}")

if 'dictionary_item_removed' in diff:
    print("\n5. 字典中删除的字段:")
    for item in diff['dictionary_item_removed']:
        print(f"  - {item}")

# 示例输出:
# ### 字典列表差异分析 ###
# 
# 1. 值变更:
#   - root[0]['age']:
#     旧值: 30
#     新值: 31
#   - root[1]['name']:
#     旧值: Bob
#     新值: Robert
#   - root[1]['hobbies'][1]:
#     旧值: swimming
#     新值: hiking
# 
# 2. 新增项:
#   - root[3]
# 
# 3. 删除项:
#   - root[2]
# 
# 4. 字典中新增的字段:
#   - root[3]['extra']    